import React from 'react'
import {AppState, DeviceEventEmitter, NativeAppEventEmitter} from 'react-native'
import propTypes from 'prop-types'
import JPushModule from 'jpush-react-native';
import {Toast} from 'antd-mobile'
import { Actions } from 'react-native-router-flux'
import {urlReg } from './utils/Reg'
let shareInstance = null;
export default class PushHandle {
    constructor(props) {
        console.log('构造方法');
        shareInstance = this;
        this._handleAppStateChange = this._handleAppStateChange.bind(this);
        this.appState = AppState.currentState;//inactive background active
        PushHandle.setBadge(0);
    }

    /***
     * 初始化
     * @param {Object|require} props
     */
    static init(props) {
        ///监听应用程序更改
        AppState.addEventListener('change', this.shareInstance(props)._handleAppStateChange);
        ///监听：应用没有启动的状态点击推送打开应用
        JPushModule.addOpenNotificationLaunchAppListener((e) => {
            console.log('应用没有启动的状态点击推送打开应用', e);
            this.setBadge(0);
        });

        ///监听：应用连接已登录
        JPushModule.addnetworkDidLoginListener((e) => {
            console.log('应用连接已登录',e);
        });

        ///监听：接收推送事件
        JPushModule.addReceiveNotificationListener((e) => {
            JPushModule.getBadge((number)=>{
                this.setBadge(number+1);
            });
            console.log('收到通知', e);
        });

        ///监听：点击推送事件
        JPushModule.addReceiveOpenNotificationListener((e) => {
            console.log('点击推送事件', e);
            if(urlReg.test(e.data)){
                Actions.web({source:{uri:e.data}});
            }
            PushHandle.setBadge(0)
        });

        ///监听：收到 Native 下发的 extra 事件
        JPushModule.addReceiveExtrasListener((e)=>{
            console.log('收到 Native 下发的 extra 事件', e);
        })

    }

    /***
     * 单例 获取实例
     * @param {Object} props
     * @returns a instance of PushHandle
     */
    static shareInstance(props) {
        if (!shareInstance) {
            shareInstance = new this(props);
        }
        return shareInstance;
    }

    /***
     * 设置应用程序徽标
     * @param {Number}number
     */
    static setBadge(number) {
        JPushModule.setBadge(number, (success) => {
            if (success) {
                console.log('清除徽标成功', success);
            }
        })
    }


    /**
     * 设置推送别名
     * @param alias
     */
    static setAlias(alias){

        JPushModule.setAlias(alias+'',(success)=>{
            console.log('设置别名成功!!!!',alias,success);
        })
    }
    /***
     * 清除监听
     */
    static destroy() {
        AppState.removeEventListener('change', this._handleAppStateChange);
        DeviceEventEmitter.removeAllListeners();
        NativeAppEventEmitter.removeAllListeners();
    }

    /***
     * 监听 应用状态更改
     * @param {string} state
     * @private
     */
    _handleAppStateChange(state) {
        console.log('应用状态更改', state);
        this.appState = state;
    }
};

